//
//  QZRegisterVC.m
//  map
//
//  Created by 000 on 16/8/18.
//  Copyright © 2016年 faner. All rights reserved.
//

#import "QZRegisterVC.h"
//#import "QZVerifyCodeVC.h"
#import "QZConfigs.h"
#import "QZLoginVC.h"

#import <BmobSDK/Bmob.h>
#import <BmobSDK/BmobSMS.h>
#import "AFNetworking.h"
@interface QZRegisterVC ()
{
    NSUserDefaults *userDefaults1;
    NSString *strRandom;
}
//验证码
@property (weak, nonatomic) IBOutlet UITextField *registerTF;//验证码
@property (weak, nonatomic) IBOutlet UITextField *userPhoneTextF;//用户名
@property (weak, nonatomic) IBOutlet UITextField *pswTextFiled;//密码

//下一步
- (IBAction)nextBtnClick:(id)sender;
//获取验证码
- (IBAction)getRegBtnClick:(id)sender;


@end

@implementation QZRegisterVC

- (void)viewDidLoad {
    [super viewDidLoad];
    userDefaults1 = [NSUserDefaults standardUserDefaults];
    [self.userPhoneTextF becomeFirstResponder];
    UITapGestureRecognizer *tapGest = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
    [self.view addGestureRecognizer:tapGest];
    
    [self addTitle];
}

- (void)tap:(UIGestureRecognizer *)tapGesture
{
    [self.userPhoneTextF resignFirstResponder];
    [self.pswTextFiled resignFirstResponder];
    [self.registerTF resignFirstResponder];
}
//添加自定义标题
-(void)addTitle
{
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0 , 60, 44)];
    titleLabel.font = [UIFont boldSystemFontOfSize:18];  //设置文本字体与大小
    titleLabel.textColor = [UIColor whiteColor];  //设置文本颜色
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = @"注册";  //设置标题
    self.navigationItem.titleView = titleLabel;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//判断手机号码是否正确
- (void)validateMobile
{
    if ([QZConfigs validateMobile:self.phoneTextField.text]) {
        //发送验证码
        [self loadData2];
    }
    else if ([self.phoneTextField.text length]==0){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请输入手机号" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"手机号验证失败,请确认手机号的正确性" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }

}
//验证码的正确
- (void)verify
{
    if ([self.registerTF.text isEqualToString:strRandom]) {
        BmobUser *bUser = [[BmobUser alloc]init];
        [bUser setUsername:self.userPhoneTextF.text];
        [bUser setPassword:self.pswTextFiled.text];
        
        [bUser signUpInBackgroundWithBlock:^(BOOL isSuccessful, NSError *error) {
            if (isSuccessful) {
                [self saveThirdCound];
                [self.navigationController popViewControllerAnimated:YES];
            } else {
            }
        }];
    }
    else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"验证码错误" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
}

- (void)saveThirdCound
{
    BmobObject *object = [BmobObject objectWithClassName:@"thirdCount"];
    [object setObject:self.userPhoneTextF.text forKey:@"loginUser"];
    
    NSString *thirdCount = [NSString stringWithFormat:@"%d",0];
    [object setObject:thirdCount forKey:@"thirdC"];
    [object setObject:thirdCount forKey:@"witchCount"];
    
    [object saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
        if (isSuccessful) {
            
        } else {
            //            NSLog(@"%@",error);
        }
    }];
    
}

//确定
- (IBAction)nextBtnClick:(id)sender {
    //验证码是否正确
    [self verify];
}
//获取验证码
- (IBAction)getRegBtnClick:(id)sender {
    
    [self validateMobile];
    
    
    self.numPhone = self.phoneTextField.text;
}

- (void)postVerify
{
    
    //1.请求管理者
    AFHTTPRequestOperationManager *manager =[AFHTTPRequestOperationManager manager];
    //2.拼接请求参数
    NSString *account = @"jk_cs_cd0";
    NSString *pswd = @"Tch654321";
    NSString *mobile = self.phoneTextField.text;
    strRandom = @"";
    for (int i = 0; i<6; i++) {
        strRandom = [strRandom stringByAppendingFormat:@"%i",(arc4random()%9)];
    }
    
    NSString *msg = [NSString stringWithFormat:@"[Map]您好，您的验证码为%@",strRandom];
    NSString *ture1 = @"ture";
    //    BOOL needstatus;
    //    NSURL *url = [NSURL URLWithString:@"http://sapi.253.com/msg/HttpBatchSendSM"];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"account"] = account;
    params[@"pswd"] = pswd;
    params[@"mobile"] = mobile;
    params[@"msg"] = msg;
    params[@"needstatus"] = ture1;
    [manager GET:@"http://sapi.253.com/msg/HttpBatchSendSM" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {nil;
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        nil;
    }];
}
- (void)loadData2
{
    NSString *account = @"N6470290";
    NSString *pswd = @"Ps8a1a0e";
    NSString *mobile = self.phoneTextField.text;
    strRandom = @"";
    for (int i = 0; i<6; i++) {
        strRandom = [strRandom stringByAppendingFormat:@"%i",(arc4random()%9)];
    }
    NSString *ture1 = @"ture";
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"account"] = account;
    params[@"pswd"] = pswd;
    params[@"mobile"] = mobile;
    params[@"needstatus"] = ture1;
    NSString *urlStr = [NSString stringWithFormat:@"http://zapi.253.com/msg/HttpBatchSendSM?account=%@&pswd=%@&mobile=%@&msg=【Map】您好，您的注册验证码是：%@.请完成注册&needstatus=true",account,pswd,mobile,strRandom];
    //转码
    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    //URL中不能包含中文 得对中文进行转码
    NSURL *url = [NSURL URLWithString:urlStr];
    NSLog(@"url = %@",url);
    //创建一个请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //主队列
    NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
    //发送一个异步请求（在子线程发送请求）
    //参数中的queue 是用来存放completionHandler任务的队列
    [NSURLConnection sendAsynchronousRequest:request queue:mainQueue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        //这个block会在请求完毕的时候自动调用
        if (connectionError) {
            NSLog(@"111");
            return ;
        } else {
            //解析服务器返回的JSON数据
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSString *error = dict[@"error"];
            if (error) {
                NSLog(@"%@",error);
            } else {
                NSLog(@"22");
            }
        }
        
    }];
    
}

@end
